<template>
  <div class="menu-authority-container">
    <t-card title="菜单权限管理" subtitle="管理系统菜单和权限" class="authority-card">
      <template #actions>
        <t-button theme="primary" @click="handleAddRoot">添加根菜单</t-button>
        <t-button @click="handleRefresh" :loading="loading">刷新</t-button>
      </template>
      
      <div class="content-area">
        <div class="tree-container">
          <t-loading :loading="loading">
            <t-tree
              :data="treeData"
              :keys="{ value: 'id', label: 'text', children: 'children' }"
              hover
              activable
              :active-multiple="false"
              :expand-all="true"
              @active="onSelect"
              @click="onNodeClick"
            >
              <template #operations="{ node }">
                <t-space>
                  <t-tooltip content="添加子菜单" v-if="node.data.type !== '1'">
                    <t-button theme="primary" variant="text" size="small" @click.stop="handleAdd(node.data.id)">
                      <template #icon><t-icon name="add" /></template>
                    </t-button>
                  </t-tooltip>
                  <t-tooltip content="编辑菜单">
                    <t-button theme="warning" variant="text" size="small" @click.stop="handleEdit(node.data.id)">
                      <template #icon><t-icon name="edit" /></template>
                    </t-button>
                  </t-tooltip>
                  <t-tooltip content="删除菜单">
                    <t-button theme="danger" variant="text" size="small" @click.stop="handleDelete(node.data.id, node.data.text)">
                      <template #icon><t-icon name="delete" /></template>
                    </t-button>
                  </t-tooltip>
                </t-space>
              </template>
            </t-tree>
          </t-loading>
        </div>
        
        <t-divider layout="vertical" />
        
        <div class="detail-container" v-if="selectedNode">
          <h3>菜单详情</h3>
          <t-descriptions bordered :column="1">
            <t-descriptions-item label="名称">{{ selectedNode.text }}</t-descriptions-item>
            <t-descriptions-item label="ID">{{ selectedNode.id }}</t-descriptions-item>
            <t-descriptions-item label="权限标识">{{ selectedNode.permission }}</t-descriptions-item>
            <t-descriptions-item label="类型">
              {{ selectedNode.type === '0' ? '菜单' : '按钮' }}
            </t-descriptions-item>
            <t-descriptions-item label="组件路径" v-if="selectedNode.component">
              {{ selectedNode.component }}
            </t-descriptions-item>
            <t-descriptions-item label="排序" v-if="selectedNode.order">
              {{ selectedNode.order }}
            </t-descriptions-item>
            <t-descriptions-item label="创建时间" v-if="selectedNode.createTime">
              {{ selectedNode.createTime }}
            </t-descriptions-item>
            <t-descriptions-item label="修改时间" v-if="selectedNode.modifyTime">
              {{ selectedNode.modifyTime }}
            </t-descriptions-item>
          </t-descriptions>
        </div>
      </div>
    </t-card>
    
    <!-- 菜单表单对话框 -->
    <t-dialog
      :visible="modalVisible"
      :header="modalTitle"
      width="600px"
      :confirm-btn="{ content: '确定', loading: confirmLoading }"
      :cancel-btn="{ content: '取消' }"
      @confirm="handleModalOk"
      @cancel="handleModalCancel"
      @close="modalVisible = false"
    >
      <t-form 
        ref="form"
        :data="formData" 
        :rules="rules"
        :label-width="100"
      >
        <t-form-item label="上级菜单" name="parentId">
          <t-tree-select
            v-model="formData.parentId"
            :data="treeSelectData"
            :keys="{ value: 'id', label: 'text', children: 'children' }"
            placeholder="请选择上级菜单"
            clearable
            :disabled="formData.id === '0'"
            @change="handleParentChange"
          />
        </t-form-item>
        <t-form-item label="菜单名称" name="text">
          <t-input v-model="formData.text" placeholder="请输入菜单名称" />
        </t-form-item>
        <t-form-item label="菜单类型" name="type">
          <t-radio-group v-model="formData.type">
            <t-radio value="0">菜单</t-radio>
            <t-radio value="1">按钮</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item label="权限标识" name="permission">
          <t-input v-model="formData.permission" placeholder="例如：menu:view" />
        </t-form-item>
        <t-form-item label="组件路径" name="component" v-if="formData.type === '0'">
          <t-input v-model="formData.component" placeholder="例如：/menu/authority" />
        </t-form-item>
        <!-- <t-form-item label="路由路径" name="path" v-if="formData.type === '0'">
          <t-input v-model="formData.path" placeholder="例如：/menu/authority" />
        </t-form-item> -->
        <t-form-item label="菜单图标" name="icon" v-if="formData.type === '0'">
          <t-input v-model="formData.icon" placeholder="图标名称" />
        </t-form-item>
        <t-form-item label="排序" name="order" v-if="formData.type === '0'">
          <t-input-number v-model="formData.order" :min="0" style="width: 100%" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script>
import Vue from 'vue';
import { MessagePlugin } from 'tdesign-vue';
import { getMenu, postMenu, deleteMenu, putMenu } from '@/service/menu';

// 导入模拟数据，实际使用中可替换为API请求
// import { menuList } from './mock';

export default Vue.extend({
  name: 'MenuAuthority',
  data() {
    return {
      loading: false,
      treeData: [],
      treeSelectData: [], // 用于选择上级菜单的树形数据
      selectedNode: null,
      modalVisible: false,
      modalTitle: '添加菜单',
      confirmLoading: false,
      isEdit: false,
      
      // 表单数据
      formData: {
        id: '',  // 对应 menuId
        text: '', // 对应 menuName
        title: '',
        type: '0',
        permission: '', // 对应 perms
        component: '',
        icon: '',
        order: 0, // 对应 orderNum
        parentId: '0',
        parentName: '顶级菜单',
        path: '', // 新增path字段
      },
      
      // 表单验证规则
      rules: {
        text: [{ required: true, message: '请输入菜单名称' }],
        // permission: [{ required: true, message: '请输入权限标识' }],
        component: [{ required: false, message: '请输入组件路径' }],
        path: [{ required: false, message: '请输入路由路径' }]
      }
    };
  },
  
  mounted() {
    this.fetchMenuData();
  },
  
  methods: {
    // 获取菜单数据
    async fetchMenuData() {
      this.loading = true;
      try {
        // 实际项目中使用以下API请求
        const res = await getMenu({});
        console.log('菜单数据:', res);
        
        // 处理数据
        if (res && res.data && res.data.rows) {
          let rootData = res.data.rows;
          
          // 如果顶层是root，修改名称
          if (rootData.text === 'root') {
            rootData.text = '顶级菜单';
          }
          
          // 确保数据结构正确
          this.treeData = [rootData];
          
          // 准备树形选择器数据
          this.prepareTreeSelectData();
        } else {
          // 如果没有数据，显示空的树
          this.treeData = [{
            id: '0',
            text: '顶级菜单',
            children: []
          }];
          this.prepareTreeSelectData();
          MessagePlugin.warning('未获取到菜单数据');
        }
      } catch (error) {
        console.error('获取菜单数据失败', error);
        MessagePlugin.error('获取菜单数据失败');
        
        // 出错时显示空树
        this.treeData = [{
          id: '0',
          text: '顶级菜单',
          children: []
        }];
        this.prepareTreeSelectData();
      } finally {
        this.loading = false;
      }
    },
    
    // 准备树形选择器数据
    prepareTreeSelectData() {
      // 创建顶级选项
      const topOption = {
        id: '0',
        text: '顶级菜单',
        children: []
      };
      
      // 深拷贝树形数据用于选择器
      const processNode = (node) => {
        // 只有菜单类型（type=0）才能作为父级
        if (node.type === '1') {
          return null;
        }
        
        const newNode = {
          id: node.id,
          text: node.text,
          children: []
        };
        
        if (node.children && node.children.length > 0) {
          node.children.forEach(child => {
            const processedChild = processNode(child);
            if (processedChild) {
              newNode.children.push(processedChild);
            }
          });
        }
        
        return newNode;
      };
      
      // 处理所有节点
      if (this.treeData && this.treeData.length > 0) {
        const rootNode = this.treeData[0];
        if (rootNode.children && rootNode.children.length > 0) {
          rootNode.children.forEach(child => {
            const processedChild = processNode(child);
            if (processedChild) {
              topOption.children.push(processedChild);
            }
          });
        }
      }
      
      this.treeSelectData = [topOption];
    },
    
    // 处理父级菜单变更
    handleParentChange(value) {
      // 当选择了新的父级菜单时，更新父级菜单名称
      this.formData.parentId = value;
      
      if (value === '0') {
        this.formData.parentName = '顶级菜单';
        return;
      }
      
      // 查找父节点名称
      const findNodeName = (list, id) => {
        for (const item of list) {
          if (item.id === id) {
            return item.text;
          }
          if (item.children && item.children.length > 0) {
            const found = findNodeName(item.children, id);
            if (found) return found;
          }
        }
        return null;
      };
      
      const parentName = findNodeName(this.treeData, value);
      if (parentName) {
        this.formData.parentName = parentName;
      }
    },
    
    // 点击节点
    onNodeClick(context) {
      console.log('点击节点:', context);
    },
    
    // 选择节点
    onSelect(value, context) {
      console.log('选择节点:', value, context);
      if (value && value.length > 0 && context && context.node) {
        this.selectedNode = context.node.data;
      } else {
        this.selectedNode = null;
      }
    },
    
    // 编辑菜单
    handleEdit(id) {
      // 查找节点
      const findNode = (list, id) => {
        for (const item of list) {
          if (item.id === id) {
            return item;
          }
          if (item.children && item.children.length > 0) {
            const found = findNode(item.children, id);
            if (found) return found;
          }
        }
        return null;
      };
      
      const node = findNode(this.treeData, id);
      if (node) {
        // 填充表单
        this.formData.id = node.id;
        this.formData.text = node.text || node.menuName;
        this.formData.title = node.title || node.text || node.menuName;
        this.formData.type = node.type;
        this.formData.permission = node.permission || node.perms;
        this.formData.component = node.component || '';
        this.formData.path = node.path || '';
        this.formData.icon = node.icon || '';
        this.formData.order = node.order || node.orderNum || 0;
        this.formData.parentId = node.parentId || '0';
        
        // 查找父节点名称
        if (node.parentId && node.parentId !== '0') {
          const parent = findNode(this.treeData, node.parentId);
          this.formData.parentName = parent?.text || '顶级菜单';
        } else {
          this.formData.parentName = '顶级菜单';
        }
        
        // 更新树选择器数据，排除自己和子菜单
        this.updateTreeSelectDataForEdit(id);
        
        this.modalTitle = '编辑菜单';
        this.modalVisible = true;
        this.isEdit = true;
      }
    },
    
    // 更新树选择器数据，排除当前节点及其子节点
    updateTreeSelectDataForEdit(currentId) {
      // 先重新准备完整的树选择数据
      this.prepareTreeSelectData();
      
      // 获取当前节点及其所有子节点ID
      const excludeIds = [];
      
      const collectChildIds = (list, id) => {
        for (const item of list) {
          if (item.id === id) {
            excludeIds.push(id);
            if (item.children && item.children.length > 0) {
              collectChildrenIds(item.children);
            }
            return true;
          }
          if (item.children && item.children.length > 0) {
            if (collectChildIds(item.children, id)) {
              return true;
            }
          }
        }
        return false;
      };
      
      const collectChildrenIds = (children) => {
        if (!children || !children.length) return;
        
        children.forEach(child => {
          excludeIds.push(child.id);
          if (child.children && child.children.length > 0) {
            collectChildrenIds(child.children);
          }
        });
      };
      
      // 收集当前节点及其子节点ID
      collectChildIds(this.treeData, currentId);
      
      // 现在过滤树选择器数据
      const filterNodes = (nodes) => {
        if (!nodes || !nodes.length) return [];
        
        return nodes.map(node => {
          // 如果当前节点需要排除，返回null
          if (excludeIds.includes(node.id)) {
            return null;
          }
          
          // 处理子节点
          const filteredChildren = filterNodes(node.children);
          
          // 返回过滤后的节点
          return {
            ...node,
            children: filteredChildren
          };
        }).filter(Boolean); // 过滤掉null值
      };
      
      // 应用过滤
      if (this.treeSelectData && this.treeSelectData.length > 0) {
        const topOption = this.treeSelectData[0];
        topOption.children = filterNodes(topOption.children);
        this.treeSelectData = [topOption];
      }
    },
    
    // 添加根菜单
    handleAddRoot() {
      this.resetForm();
      this.formData.parentId = '0';
      this.formData.parentName = '顶级菜单';
      this.modalTitle = '添加根菜单';
      this.modalVisible = true;
      this.isEdit = false;
      
      // 恢复完整的树选择器数据
      this.prepareTreeSelectData();
    },
    
    // 添加子菜单
    handleAdd(parentId) {
      console.log('添加子菜单, 父ID:', parentId);
      this.resetForm();
      
      // 查找父节点
      const findParent = (list, id) => {
        for (const item of list) {
          if (item.id === id) {
            return item;
          }
          if (item.children && item.children.length > 0) {
            const found = findParent(item.children, id);
            if (found) return found;
          }
        }
        return null;
      };
      
      const parent = findParent(this.treeData, parentId);
      if (parent) {
        this.formData.parentId = parent.id;
        this.formData.parentName = parent.text;
      } else {
        console.warn('未找到父节点:', parentId);
      }
      
      // 恢复完整的树选择器数据
      this.prepareTreeSelectData();
      
      this.modalTitle = '添加子菜单';
      this.modalVisible = true;
      this.isEdit = false;
    },
    
    // 删除菜单
    handleDelete(id, name) {
      this.$dialog({
        header: '确认删除',
        body: `确定要删除菜单"${name}"吗？如果存在子菜单，将一并删除。`,
        confirmBtn: { theme: 'danger', content: '确认' },
        cancelBtn: { content: '取消' },
        onConfirm: async () => {
          try {
            // 实际项目中使用以下API请求
            await deleteMenu({ id });
            
            MessagePlugin.success('删除成功');
            // 重新加载数据
            this.fetchMenuData();
            
            // 如果当前选中的是被删除的节点，清空选中
            if (this.selectedNode && this.selectedNode.id === id) {
              this.selectedNode = null;
            }
          } catch (error) {
            console.error('删除失败', error);
            MessagePlugin.error('删除失败');
          }
        }
      });
    },
    
    // 提交表单
    handleModalOk() {
      if (!this.$refs.form) {
        console.error('表单引用不存在');
        return;
      }
      
      this.$refs.form.validate().then(async (result) => {
        if (result === true) {
          this.confirmLoading = true;
          
          try {
            // 构建API需要的数据格式
            const apiData = {
              menuId: this.isEdit ? Number(this.formData.id) : undefined, // 编辑时需要menuId
              menuName: this.formData.text,
              type: this.formData.type,
              perms: this.formData.permission,
              component: this.formData.component,
              path: this.formData.path,
              icon: this.formData.icon,
              orderNum: Number(this.formData.order),
              parentId: Number(this.formData.parentId)
              // 其他字段如createTime等由后端处理
            };
            
            console.log('提交数据:', apiData);
            
            if (this.isEdit) {
              // 编辑菜单
              await putMenu(apiData);
              MessagePlugin.success('更新成功');
            } else {
              // 添加菜单
              await postMenu(apiData);
              MessagePlugin.success('添加成功');
            }
            
            this.modalVisible = false;
            // 重新加载数据
            await this.fetchMenuData();
          } catch (error) {
            console.error('操作失败', error);
            MessagePlugin.error('操作失败' + (error.message ? `: ${error.message}` : ''));
          } finally {
            this.confirmLoading = false;
          }
        }
      }).catch(errors => {
        console.log('表单验证失败', errors);
        MessagePlugin.warning('表单填写有误，请检查');
      });
    },
    
    // 取消表单
    handleModalCancel() {
      this.modalVisible = false;
      this.resetForm();
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        id: '',
        text: '',
        title: '',
        type: '0',
        permission: '',
        component: '',
        path: '',
        icon: '',
        order: 0,
        parentId: '0',
        parentName: '顶级菜单'
      };
      
      if (this.$refs.form) {
        this.$refs.form.reset();
      }
    },
    
    // 刷新
    handleRefresh() {
      this.fetchMenuData();
    }
  }
});
</script>

<style lang="less" scoped>
.menu-authority-container {
  padding: 20px;
  
  .authority-card {
    .content-area {
      display: flex;
      margin-top: 20px;
      
      .tree-container {
        width: 50%;
        padding-right: 20px;
        overflow: auto;
        max-height: calc(100vh - 280px);
      }
      
      .detail-container {
        width: 50%;
        padding-left: 20px;
        
        h3 {
          margin-top: 0;
          margin-bottom: 20px;
        }
      }
    }
  }
}
</style>
